extends Node
var canhero = true
var x1:int = 0
var path
var cons
var base
var spoint:int = 0
var piece:int = 0
var crystal:int = 0
var spiece:int = 0
var jt:int = 0
var mfq:int = 0
var sf:int = 0
var sp:int = 0
var txz:int = 0
var ypz:int = 0
var sq = 0#是否点神器天赋
var zx = null#是否点阵型天赋
var globalBonus
var ctrl
var st = ["cex___Hide_dragon1","cex___Hide_dragon2","cex___Hide_dragon3","cex___Hide_dragon4","cex___Hide_pet1","cex___Hide_pet2","cex___Hide_pet3","cex___Hide_skull1","cex___Hide_skull2","cex___Hide_totem1","cex___Hide_totem2","cex___Hide_totem3","cex___Hide_tree1","cex___Hide_tree2","cex___Hide_tree3","cex___Hide_tree4","cex___Hide_tree5"]#召唤石种类
var x2 = []#1级兵
var x3 = []#2级兵
var x4 = []#3级兵
var x5 = []#4级兵
#以上用于随机抽取和开局随机
var rareItem:int = 15#稀有装备获取概率
#左
const cellsLeft = [
	Vector2(0,0), Vector2(1,0), Vector2(2,0), Vector2(3,0), Vector2(4,0),

	Vector2(0,1), Vector2(1,1), Vector2(2,1), Vector2(3,1), Vector2(4,1),

	Vector2(0,2), Vector2(1,2), Vector2(2,2), Vector2(3,2), Vector2(4,2),

	Vector2(0,3), Vector2(1,3), Vector2(2,3), Vector2(3,3), Vector2(4,3),

	Vector2(0,4), Vector2(1,4), Vector2(2,4), Vector2(3,4), Vector2(4,4),

	Vector2(0,5), Vector2(1,5), Vector2(2,5), Vector2(3,5), Vector2(4,5)
]
#右
const cellsRight = [
	Vector2(5,0), Vector2(6,0), Vector2(7,0), Vector2(8,0), Vector2(9,0),

	Vector2(5,1), Vector2(6,1), Vector2(7,1), Vector2(8,1), Vector2(9,1),

	Vector2(5,2), Vector2(6,2), Vector2(7,2), Vector2(8,2), Vector2(9,2),

	Vector2(5,3), Vector2(6,3), Vector2(7,3), Vector2(8,3), Vector2(9,3),

	Vector2(5,4), Vector2(6,4), Vector2(7,4), Vector2(8,4), Vector2(9,4),

	Vector2(5,5), Vector2(6,5), Vector2(7,5), Vector2(8,5), Vector2(9,5)
]
func _ready():
	pass
func _init():
	print("塔防之光基础：加载完成")
	call_deferred("AneHekUtilsInit")
	pass
func _connect():
	pass
#初始化
func AneHekUtilsInit():
	base = globalData.infoDs["g_AneHekBase"]
	ctrl = globalData.infoDs["g_AneHek"]
	path = chaData.infoDs["cTDW"].dir
	cons = load("%s/cons.gd" % path).new()
	globalBonus = globalData.infoDs["g_AneHekGB"]
	base.connect("onNewGame",self,"initdata")
	base.connect("onLoadGame",self,"getdata")
#初始化数据
func initdata():
	if !ctrl.allflag:return
	canhero = true
	base.setData("canhero",true)
	piece = 0
	crystal = 0
	spiece = 0
	spoint = 4
	jt = 0
	mfq = 0
	sf = 0
	sp = 0
	txz = 0
	ypz = 0
	var node = sys.main.get_node("ui")
	var tr = cTr("test/msgbg.png")
	node.add_child(tr)
	tr.set_position(Vector2(525,100))
	var txt = "[color=red]\t\t\t\t\t\t\t\t           开局赠送4点技能点\n  【用于解锁/升级英雄技能[2/1点]；过关随机赠送】[/color]\n[color=blue]\t\t\t\t\t\t           当前游玩模式："
	if base.getSetting("expertMode", false):
		txt += "[color=red]专家模式[/color]\n\t\t\t\t【玩家血量上限:100；每回合回血:0】"
	elif base.getSetting("normalMode", false):
		txt += "[color=red]普通模式[/color]\n\t\t\t\t 【玩家血量上限:400；每回合回血:20】"
	else:
		txt += "[color=red]简单模式[/color]\n\t\t\t\t 【玩家血量上限:400；每回合回血:回满】"
	txt += "[color=#ffa500]Tips:普通角色（非英雄）升级每级+150点血，10防，17点攻击；满级五级；升级材料过关赠送材料中随机获得；进化清除等级，不返回升级花费；升级属性开始战斗后起效"
	var lb = cRLb(txt,tr,Vector2(535,400))
	lb.rect_position = Vector2(50,110)
	cBtns(tr,self,"确定","readit",[tr],Vector2(285,450))
	#sys.newBaseMsg("欢迎游玩","开局赠送4点技能点\n【用于解锁英雄技能[2点]和升级英雄技能[1点]；获取方式：过关随机赠送】")
	if sys.test:spoint = 10
	var diff = int(base.getSetting("difficult",1))
	if diff > 14:
		sys.newBaseMsg("提示","血量保护机制[玩家血量加成&敌方造成伤害有上限]已开启，持续至27层")
	refesh3()
#确定
func readit(tr):
	tr.queue_free()
#获取数据
func getdata():
	if !ctrl.allflag:return
#	piece =  base.data.piece
#	crystal = base.data.crystal
#	spiece = base.data.spiece
	spoint = base.data.spoint
	canhero = base.data.canhero
	jt = base.data.jt
	mfq = base.data.mfq
	sf = base.data.sf
	sp = base.data.sp
	txz = base.data.txz
	ypz = base.data.ypz
#——————————————————————————————————————————————————————创建控件类——————————————————————————————————————————————————————#
#根据配置文件创建按钮
func cBtn(id, baseNode, obj):
	var cfg = cons.buttoncfg.get(id)
	var btn = Button.new()
	btn.text = cfg.text
	if cfg.has("position"):
		btn.rect_position = cfg.position
	if not cfg.has("args"):
		cfg["args"] = []
	if cfg.has("shortCut"):
		var sc = ShortCut.new()
		var ky = InputEventKey.new()
		ky.scancode = cfg.shortCut
		sc.set_shortcut(ky)
		btn.shortcut = sc
		btn.shortcut_in_tooltip = true
	btn.connect("pressed", obj, cfg.conn, cfg.args)
	baseNode.add_child(btn)
	btn.enabled_focus_mode = 0
	return btn
#根据参数创建按钮
func cBtns(baseNode, bindInstance, text, callback, args = [],position = Vector2(90,170)):
	var btn = Button.new()
	btn.rect_position = position
	btn.text = text
	btn.connect("pressed", bindInstance, callback, args)
	baseNode.add_child(btn)
	btn.enabled_focus_mode = 0
	return btn
#创建文本框
func cLb(text, baseNode):
	var lb = Label.new()
	lb.text = text
	baseNode.add_child(lb)
	return lb
#创建富文本框
func cRLb(text, baseNode, size = Vector2(580,50)):
	var lb = RichTextLabel.new()
	lb.bbcode_text = text
	lb.bbcode_enabled = true
	lb.push_align(0)
	lb.set_custom_minimum_size(size)
	lb.name = "RichTextLabel"
	baseNode.add_child(lb)
	return lb
#创建图片容器
func cTr(file):
	var obj = TextureRect.new()
	obj.set_texture(base.loadImg(path, file))
	return obj
#创建图片
func cIt(file):
	#path = chaData.infoDs["cTDW"].dir
	#print(path,file)
	return base.loadImg(path, file)
#创建窗口
func cWin(baseNode, title, size = Vector2(900, 500)):
	var window = WindowDialog.new()
	window.set_size(size)
	window.window_title = title
	baseNode.add_child(window)
	return window
#创建滚动容器
func cSc(baseNode, size, position):
	var context = ScrollContainer.new()
	context.set_custom_minimum_size(size)
	context.rect_position = position
	baseNode.add_child(context)
	return context
#创建竖向容器
func cHb(baseNode):
	var itemBox = HBoxContainer.new()
	baseNode.add_child(itemBox)
	return itemBox
#创建横向容器
func cVb(baseNode):
	var itemBox = VBoxContainer.new()
	baseNode.add_child(itemBox)
	return itemBox
#——————————————————————————————————————————————————————创建控件类——————————————————————————————————————————————————————#
#——————————————————————————————————————————————————————单元格类——————————————————————————————————————————————————————#
#所有单元格
func getAllCells(team):
	if team == 1:
		return cellsLeft + cellsRight
	elif team == 2:
		return cellsRight + cellsLeft
#全队单元格
func getAllyCells(team):
	if team == 1:
		return cellsLeft
	elif team == 2:
		return cellsRight
#随机单元格
func getRndCell(team):
	if team == 1:
		return sys.rndListItem(cellsLeft)
	elif team == 2:
		return sys.rndListItem(cellsRight)
	else:
		return sys.rndListItem(cellsLeft + cellsRight)
#——————————————————————————————————————————————————————单元格类——————————————————————————————————————————————————————#
#——————————————————————————————————————————————————————英雄类——————————————————————————————————————————————————————#
#英雄是否在场上
func inBattle(cha):
	return sys.main.matCha(cha.get("cell")) == cha
#获取场下英雄
func getReadyChas():
	var chas = []
	for i in sys.main.btGrid.get_children():
		if i.get_children().size() == 0:continue
		var cha:Chara = i.get_child(0)
		chas.append(cha)
	return chas
#获得所有单位，0全部，1敌人，2友军
func getAllChas(team = 0):
	var result = []
	for i in getAllCells(1):
		var cha = sys.main.matCha(i)
		if cha != null:
			if team == 0 || team == 1 && cha.team == 2 || team == 2 && cha.team == 1:
				result.append(cha)
	return result
#获取英雄与目标连线上所有英雄
func lineChas(aCell, bCell, num):
	var chas = []
	var aPos = sys.main.map.map_to_world(aCell)
	var bPos = sys.main.map.map_to_world(bCell)
	var n = (bPos - aPos).normalized()
	var oldCell = null
	for i in range(num):
		var ac = sys.main.map.world_to_map(aPos)
		aPos += n * 100
		if oldCell != ac:
			oldCell = ac
			if sys.main.matCha(ac) != null:
				chas.append(sys.main.matCha(ac))
	return chas
#从cha数组中获得第一个非boss角色
func getFirstFromChas(chas):
	for i in chas:
		if i.get("type") == "BOSS":continue
		return i
#根据cha获得一个随机敌方单位
func getRndEnemy(cha):
	var chas = cha.getAllChas(1)
	if chas == null or chas.empty():
		return []
	else:
		return sys.rndListItem(chas)
#根据cha获得一个随机友方单位
func getRndAlly(cha):
	return sys.rndListItem(cha.getAllChas(2))
#从当前池子中获得随机英雄（石头：70%，三星：20%，四星：8%五星：2%）
func getRndCha(buff = 0):
	var rngnum = sys.rndRan(1, 100)
	var rng = ""
	if rngnum <= 2 + buff:
		rng = sys.rndListItem(x5)
	elif rngnum <= 8 + buff:
		rng = sys.rndListItem(x4)
	else:
		if rngnum <= 20 + buff:
			rng = sys.rndListItem(x3)
		else:#石头概率：风水火：20%，其他10%
			if sys.rndPer(60):
				rng = st[sys.rndRan(0,2)]
			else:
				rng = st[sys.rndRan(3,6)]
	return sys.main.newChara(rng)
#召唤石随机英雄
func rndCha(buff = 0) -> Chara:#x3:234,x4:345,x5:5
	#yield(sys.get_tree().create_timer(0.01), "timeout")
	var rngnum = sys.rndRan(1,1000)
	var rng = ""
	if rngnum <= 50 + buff:
		rng = sys.rndListItem(x5)
	elif rngnum <= 200 + buff:
		rng = sys.rndListItem(x4)
	elif rngnum <= 500 + buff:
		rng = sys.rndListItem(x3)
	else:
		rng = sys.rndListItem(x2)
	#print(rng)
	return  sys.main.newChara(rng)
#进化单位
func evoCha(cha,id):
	sys.main.player.addCha(sys.main.newChara(cha.id))
	sys.main.player.addCha(sys.main.newChara(cha.id))
	var cha1 = sys.main.evoChara(cha, id)
	cha1.isDrag = true
	if is_instance_valid(cha) and cha.get("manualDel") == false:
		cha.manualDel = true
	return cha1
#召唤/扭蛋结果显示
func rollItem(itm, cha, title = "抽奖结果", pos = 0):
	var xx = sys.newMsg("jiangLiMsg")#Panel->Label、Label、CenterContainer、RichTextLabel、Button
	xx.get_node("Panel/Label").text = title
	var gachaGrid = GridContainer.new()
	gachaGrid.set_columns(5)
	gachaGrid.rect_position = Vector2(150, 75)
	xx.get_node("Panel").add_child(gachaGrid)
	if itm >=1:
		var wadditem = []
		if pos:
			for i in range(itm):
				var item1
				var rnum = sys.rndRan(1,10000)
				if rnum <= 1000:
					item1 = sys.newItem(getRndItem("RARE"))
				elif rnum <= 2000:
					item1 = sys.newItem(getRndItem("NORMAL"))
				elif rnum <= 5000:
					item1 = sys.newItem(getRndItem("MYALL"))
				else:
					item1 = sys.newItem(getRndItem())
				wadditem.append(item1)
				yield(sys.get_tree().create_timer(0.01), "timeout")
		else:
			for i in range(itm):
				var item1
				item1 = sys.newItem(getRndMaterial())
				if sys.rndPer(50):
					item1 = sys.newItem(getRndMaterial2())
				wadditem.append(item1)
				yield(sys.get_tree().create_timer(0.01), "timeout")
		for i in range(itm):
			if wadditem[i].id.find("rw_") != -1:
				match wadditem[i].id.replace("i_Hide_rw_",""):
					"jt":jt += 1
					"mfq":mfq +=1
					"sf":sf += 1
					"sp":sp += 1
					"txz":txz += 1
					"ypz":ypz += 1
			else:
				sys.main.player.addItem(wadditem[i])
			var itemBt = load("res://ui/item/item.tscn").instance()
			itemBt.init(wadditem[i])
			var vbox = VBoxContainer.new()
			vbox.rect_min_size = Vector2(120, 120)
			vbox.alignment = 1#对齐方式，0是开头对齐，1是中心对齐，2是末端对齐
			vbox.add_child(itemBt)
			gachaGrid.add_child(vbox)
		if !pos && itm == 10:
			xx.get_node("Panel/RichTextLabel").bbcode_text = "材料十连额外赠送一个神发"
			sf += 1
			#sys.main.player.addItem(sys.newItem("i_Hide_rw_sf"))
	if cha >=1:
		for i in range(cha):
			var cha1 = rndCha(globalBonus.charaBuildBonus)
			while cha1 == null :
				cha1 = rndCha(globalBonus.charaBuildBonus)
			cha1.get_node("ui/hpBar").visible = false
			var chaBt=preload("res://ui/itemBt/itemBt.tscn").instance()
			chaBt.id = cha1.id
			sys.main.player.addCha(sys.main.newChara(cha1.id))
			gachaGrid.add_child(chaBt)
			yield(sys.get_tree().create_timer(0.01), "timeout")
	xx.show()	
#——————————————————————————————————————————————————————英雄类——————————————————————————————————————————————————————#
#——————————————————————————————————————————————————————特效类——————————————————————————————————————————————————————#
#人物跳跃到指定地点
func jump(target, selfCha):
	var mv = Vector2(target.cell.x ,target.cell.y)
	var vs = [Vector2(0,0),Vector2(1,0),Vector2(-1,0),Vector2(0,1),Vector2(0,-1),Vector2(1,1),Vector2(-1,1),Vector2(-1,-1),Vector2(1,-1)]
	for i in vs:
		var v = mv+i
		if sys.main.matCha(v) == null && sys.main.isMatin(v):
			if selfCha.setCell(v) :
				var pos = sys.main.map.map_to_world(selfCha.cell)
				ying(pos, selfCha)
				selfCha.position = pos
				selfCha.aiCha = null
				break
#移动特效
func ying(pos, selfCha):
	var l:Vector2 = pos - selfCha.position
	var s = 25
	var rs = preload("res://core/ying.tscn")
	var n = l.length()/s
	for i in range(n):
		var spr = rs.instance()
		sys.main.map.add_child(spr)
		spr.texture =  selfCha.img.texture_normal
		spr.position = selfCha.position + s * (i+1) * l.normalized() - Vector2(selfCha.img.texture_normal.get_width()/2,selfCha.img.texture_normal.get_height())
		spr.init(255/n * i + 100)
#——————————————————————————————————————————————————————特效类——————————————————————————————————————————————————————#
#——————————————————————————————————————————————————————装备类——————————————————————————————————————————————————————#
#获取随机装备ID
func getRndItem(type = "DEFAULT"):
	if type == "NORMAL":
		return sys.rndListItem(cons.items)
	elif type == "RARE": 
		return sys.rndListItem(cons.rareitems)
	elif type == "MYALL":
		return sys.rndListItem(cons.allitems)
	else:
		return sys.rndListItem(itemData.rndPool.items)[0].id
#获取随机材料id
func getRndMaterial():
	var list = ["rw_jt","rw_mfq","rw_sf","rw_sp","rw_txz","rw_ypz"]
	return "i_Hide_" + sys.rndListItem(list)
func getRndMaterial2():
	var list = ["cbt","fcb","fcd","fcz","ld","mwdzz","sk","yq"]
	return "i_Hide_wp_" + sys.rndListItem(list)
#三件装备升级成套装
func itemUpgrade(item):
	var masCha = item.masCha
	if masCha.isSumm:return
	yield(sys.get_tree().create_timer(0.2), "timeout")
	var n = 0
	var tmpid:String = item.id
	tmpid = tmpid.left(4)
	#print(tmpid)
	var f1 = 0
	var f2 = 0
	var f3 = 0
	for i in masCha.items:
		if i.id == tmpid + "eh" && !f1:
			n += 1
			f1 = 1
		if i.id == tmpid + "xl" && !f2:
			n += 1
			f2 = 1
		if i.id == tmpid + "jz" && !f3:
			n += 1
			f3 = 1
	if n == 3:
		var index = masCha.items.size() - 1
		while(index>=0):
			var i = masCha.items[index]
			masCha.delItem(i)
			sys.main.player.delItem(i)
			index -= 1
		var upgid = "i_Hide_" + tmpid.right(2) + "tz"
		#print(upgid)
		var nitem = sys.newItem(upgid)
		masCha.addItem(nitem)
		sys.main.player.addItem(nitem)
		#获取升级后的套装装备并装备上（待完成）
#——————————————————————————————————————————————————————读取类——————————————————————————————————————————————————————#
var changelog
var guidelog
var file = File.new()
func readChangeLog():
	if changelog == null:
		if file.file_exists(path+"/log.txt"):
			file.open(path+"/log.txt",File.READ)
			changelog=file.get_as_text()
			file.close()
		else:
			print("更新文档不存在")
			return null
	return changelog
func readGuideLog():
	if guidelog == null:
		if file.file_exists(path+"/guide.txt"):
			file.open(path+"/guide.txt",File.READ)
			guidelog=file.get_as_text()
			file.close()
		else:
			print("说明文档不存在")
			return null
	return guidelog
#——————————————————————————————————————————————————————读取类——————————————————————————————————————————————————————#
func refesh3():
	ctrl.spoints.text = "技能点：%d"%int(self.spoint)
	#ctrl.spieces = self.spiece
	#ctrl.pieces = self.piece
	#ctrl.crystals = self.crystal